import React from 'react';
import { Tools } from 'weaver-mobile';
const getLabel = Tools.getLabel;

export const openHrmCard = (id, e) => {
    window.openLink.openHrm(id);
    if (e) {
        e.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
    }
}

//将id和名称转成数组
export const idsAndNamesToArr = (ids, names) => {
    if (ids != undefined && names != undefined) {
        if (ids == "" && names == "") {
            return []
        }
        let id = ids.split(",");
        let name = names.split(",");
        let arr = [];
        for (let i = 0; i < id.length; i++) {
            arr.push({ id: id[i], name: name[i] });
        }
        return arr;
    } else {
        return [];
    }
}

//计算天数
export const DateDiffDays = (startdate, enddate) => {
    var arr = startdate.split('-');
    var starttime = new Date(arr[0], arr[1] - 1, arr[2]);
    var starttimes = starttime.getTime();
    var arrs = enddate.split('-');
    var lktime = new Date(arrs[0], arrs[1] - 1, arrs[2]);
    var lktimes = lktime.getTime();
    var days = (lktimes - starttimes) / (3600 * 1000 * 24);
    return days;
};

//获取当前周
export const getWeekOfYear = () => {
    var today = new Date();
    var firstDay = new Date(today.getFullYear(), 0, 1);
    var dayOfWeek = firstDay.getDay();
    var spendDay = 1;
    if (dayOfWeek != 0) {
        spendDay = 7 - dayOfWeek + 1;
    }
    firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
    var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
    var result = Math.ceil(d / 7);
    if (result < 2) return 1;
    return result - 1;
};
/**
 * 获取浏览器参数
 */
export const getParams = key => {
    var href = window.location.href.replace(/&#38;/g, "&");
    var reg = new RegExp("(^|\\?|&)" + key + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(href))
        return unescape(RegExp.$2.replace(/\+/g, " "));
    return "";
}
//时间转换成string
export const convertTimeToString = (date) => {
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    let currentDate = date.getFullYear() + "-" + month + "-" + strDate;
    return currentDate;
}

export const toDecimal = (value) => {
    let f = parseFloat(value);
    if (isNaN(f)) {
        return;
    }
    f = Math.round(value * 100) / 100;
    return f;
}

export const transfStr = (name = '', ids = '', list = [], type = '', relateId = '', model = '') => {
    let str = '';
    list.map(item => {
        if (name === 'Upload' && type === 'image') {
            str += '<img class="formImgPlay" src="' + item.filelink + '" data-imgsrc="' + (item.loadlink || item.filelink) + '" />'
        }
        if (name === 'Upload' && type === 'file') {
            str += `<a href='javascript:void(0)' onclick='try{openDoc(${item.fileid},${relateId},${model},this);return false;}catch(e){}' ondblclick='return false;' unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.filename}</a>
            &nbsp;<a href='javascript:void(0)' onclick='try{downloadFile(${item.fileid},${item.imagefileid},${relateId},${model},this);return false;}catch(e){}' unselectable='off' target='_blank' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${getLabel(258, '下载')}(${item.filesize})</a></br>`;
        }
        if (name === 'Browser') {
            str += `<a href='javascript:void(0)' onclick='try{openAppLink(this,${item.id},${type},${relateId},${model});return false;}catch(e){}' ondblclick='return false;'  unselectable='off' contenteditable='false' style='cursor:pointer;text-decoration:underline !important;margin-right:8px'>${item.name || item.showname}</a>&nbsp;`
        }
    })
    return str;
}

export const gUID = () => {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
//下载附件
export const downloadsDoc = (id, filesid, relateId, type,plandetailid) => {
    let options = {
        method: 'POST',
        url: '/api/workrelate/common/viewDocFiled',
        params: { id: id, relateId: relateId, type: type,plandetailid }
    }
    Tools.callApi(options).then((data) => {
        if (data.status) {
            window.openLink.getWeaverFile("/weaver/weaver.file.FileDownload?fileid=" + filesid + "&download=1")
        }
    });
}
//打开附件 id 附件id  relateId
export const opendoc = (id, relateId, type,plandetailid) => {
    let options = {
        method: 'POST',
        url: '/api/workrelate/common/viewDocFiled',
        params: { id: id, relateId: relateId, type: type,plandetailid }
    }
    Tools.callApi(options).then((data) => {
        if (data.status) {
            window.openLink.openDocument(id);
        }
    });
}
//文件属性格式化成移动端所需的格式
export const formatFiles = (filearray, canedit) => {
    let files = []
    if (filearray && filearray.length > 0) {
        files = filearray.map(f => {
            return {
                imagefileid: f.imagefileid,
                id: f.id,
                filename: f.name,
                showDelete: canedit,
                showLoad: true,
                name:f.name,
                fileid:f.id,
            }
        })
    }
    return files
}
//对比第一个字符串和（第二个数组或字符串） 找出第二个字符中删除或者第二字数组中新增的元素
export const ArrayDiffer = (str, arry, type) => {
    if (type == 1 && str.length > 0) {//删除
        if (arry.length == 0) {
            return str;
        } else {
            let res = "";
            let strArray = str.split(",");
            for (let i = 0; i < strArray.length; i++) {
                if (strArray[i] != "" && arry.indexOf(',' + strArray[i] + ',') == -1) {
                    res += strArray[i] + ",";
                }
            }
            return res;
        }
    } else if (type == 2 && arry.length > 0) {//新增
        if (str.length == 0) {
            return arry.toString();
        } else {
            let res = "";
            for (let i = 0; i < arry.length; i++) {
                if (str.indexOf(',' + arry[i] + ',') == -1) {
                    res += arry[i] + ",";
                }
            }
            return res;
        }
    }
    return "";
}

//判空处理
export const isEmpty = (obj) => {
    if (typeof obj === 'undefined' || obj == null || obj === '') {
        return true;
    } else {
        return false;
    }
}

export const myIsNaN = (value) => {
    return typeof value === 'number' && !isNaN(value);
}

//监听iphone键盘聚焦事件
export const addKeyboardFocusScrollEvent = ()=>{
    document.body.addEventListener('focusin', () => {  //软键盘弹起事件
        var scrollTop = 0;
        if (document.documentElement && document.documentElement.scrollTop) {
            scrollTop = document.documentElement.scrollTop;
        } else if (document.body) {
            scrollTop = document.body.scrollTop;
        }
        window.workrelateScrollTop = scrollTop
    });
    document.body.addEventListener('focusout', () => { //软键盘关闭事件
        var ua = window.navigator.userAgent;
        if (ua.indexOf('iPhone') > 0 || ua.indexOf('iPad') > 0) { //键盘收起页面空白问题
            document.body.scrollTop = window.workrelateScrollTop;
            document.documentElement.scrollTop = window.workrelateScrollTop;
        }
    });
}
export const startWith = (str, dim) => {
    var reg = new RegExp("^" + dim);
    return reg.test(str);
  }
  export const endWith = (str, dim) => {
    var reg = new RegExp(dim + "$");
    return reg.test(str);
  }